<?php

namespace App\Modules\Admin\Http\Controllers;

use Illuminate\Http\Request;
use App\Exceptions\ValidationException;
use App\Http\Controllers\BaseController;
use Illuminate\Support\Facades\Validator;
use App\Modules\Admin\Services\LoginService;

/**
 * @OA\Tag(
 *   name="Admin-Login",
 *   description="后台-登录"
 * )
 */
class LoginController extends BaseController
{
    protected $loginService;

    public function __construct(LoginService $loginService)
    {
        $this->loginService = $loginService;
    }

    /**
     * 登录
     *
     * @return void
     */
    public function login(Request $request)
    {
        $param = $request->only(['username', 'password', 'captcha']);
        $validator = Validator::make($param, [
            'username' => ['required'],
            'password' => ['required'],
            // 'captcha' => ['required'],
        ], [], [
            'username' => '账户',
            'password' => '密码',
            // 'captcha' => '验证码',
        ]);
        if ($validator->fails()) {
            throw new ValidationException($validator->errors()->first());
        }
       
        $result = $this->loginService->login($param);
        return $this->response->success($result);
    }

    /**
     * 获取后台验证码
     *
     * @return void
     */
    public function captcha()
    {
        $result['data'] = captcha_src('mini');
        return $this->response->success($result);
    }

    /**
     * 登出
     *
     * @param Request $request
     * @return void
     */
    public function logout(Request $request)
    {
        $adminUser = $request->user();
        $result = $this->loginService->logout($adminUser);
        return $this->response->success($result);

    }
}
